//
//  DLClearCache.m
//  EggSteward
//
//  Created by 王道林 on 16/9/13.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "DLClearCache.h"

@implementation DLClearCache

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

+ (DLClearCache *)clearCache
{
    return [[DLClearCache alloc] init];
}



// 计算清除的缓存

- (NSString *)CalculateCache
{
    //找到缓存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    //folderSizeAtPath这个方法是遍历文件夹获得文件夹大小,下面封装的.
    float size = [self folderSizeAtPath:path];
    NSString *strOfCache = [NSString stringWithFormat:@"缓存:%.1fM", size];
    return strOfCache;
}

// 遍历文件夹获得文件夹大小, 返回多少m
- (float) folderSizeAtPath:(NSString *)folderPath
{
    //创建文件管理对象,
    NSFileManager *manager = [NSFileManager defaultManager];
    // 判断路径是否存在
    if (![manager fileExistsAtPath:folderPath])
    {
        return 0;
    }
    else
    {
        NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
        NSString *fileName;
        // 用来累加缓存的folderSize
        long long folderSize = 0;
        while ((fileName = [childFilesEnumerator nextObject]) != nil)
        {
            NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
            //fileSizeAtPath方法是计算单个文件的大小, 下面封装
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        return folderSize / (1024.0 * 1024.0);
    }
}

// 计算单个文件的大小
- (long long)fileSizeAtPath:(NSString *)filePath
{
    
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
        
    }else{
        return 0;
    }
}
// 清除缓存
- (NSString *)ClearCacheAndCalculateNew
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    //遍历清除每个文件缓存
    for (NSString *p in files)
    {
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path])
        {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
    //重写计算缓存
   return [self CalculateCache];
}






@end
